package com.sram.controller.jdbcConn;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.InputStream;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Properties;

/**
 * Created by Administrator on 2017/6/9.
 */
@Controller
@RequestMapping("/JdbcConn")
public class JdbcConn {

    @RequestMapping(value="/JdbcConn")
    public  void getAllUser() throws Exception {

        String passMd5 = new Md5Hash("751701","duhao").toString();
//        GetMd5Hash(input);
         Connection conn = null;
         PreparedStatement pst = null;
        ResultSet rs =null ;
        // 读取配置文件
        InputStream in = JdbcConn.class.getClassLoader().getResourceAsStream("/jdbc.properties");
        // 加载配置文件
        Properties properties = new Properties();
        properties.load(in);
        // 获取数据库连接
        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url") + "?useUnicode=true&characterEncoding=utf-8";
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");

        Class.forName(driver);
        conn = (Connection) DriverManager.getConnection(url,username,password);
        long a=System.currentTimeMillis();
        conn.setAutoCommit(false); // 开启事物
        for (int i = 0; i < 100 ; i++) {
            pst = (PreparedStatement) conn.prepareStatement("INSERT INTO t_user values (null,'duhao','dh')", Statement.RETURN_GENERATED_KEYS);//准备执行语句
            pst.executeUpdate();
            // 返回自动生成的键
            rs = pst.getGeneratedKeys();
            if (rs.next()) {
                System.out.println( rs.getInt(1));

            }
        }


        conn.commit(); // 提交事物
        System.out.println("\r<br>执行耗时 : "+(System.currentTimeMillis()-a)/1000f+" 秒 ");
        conn.close();
        pst.close();
    }
}
